package com.qfedu.dtboot.service.impl;

import com.qfedu.dtboot.dao.SysMenuMapper;
import com.qfedu.dtboot.dao.SysUserMapper;
import com.qfedu.dtboot.entity.SysMenu;
import com.qfedu.dtboot.entity.SysUser;
import com.qfedu.dtboot.service.SysUserService;
import com.qfedu.dtboot.utils.DataGridResult;
import com.qfedu.dtboot.utils.Query;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * Created by helen on 2018/3/6
 */
@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysMenuMapper sysMenuMapper;

    @Override
    public DataGridResult getPageList(Query query) {
        List<SysUser> rows = sysUserMapper.queryList(query);
        int total = sysUserMapper.queryTotal(query);
        DataGridResult dataGridResult = new DataGridResult(rows, total);
        return dataGridResult;
    }

    @Override
    public void deleteBatch(Long[] userId) {

        sysUserMapper.deleteBatch(userId);
    }

    @Override
    public void save(SysUser sysUser) {
        sysUser.setCreateTime(new Date());
        sysUser.setCreateUserId(1L);
        sysUserMapper.insertSelective(sysUser);

    }

    @Override
    public SysUser queryObject(Long userId) {
        SysUser sysUser = sysUserMapper.selectByPrimaryKey(userId);
        return  sysUser;
    }

    @Override
    public void update(SysUser sysUser) {
        sysUserMapper.updateByPrimaryKeySelective(sysUser);

    }

    @Override
    public SysUser queryByUserName(String username) {

        return sysUserMapper.queryByUserName(username);
    }

    @Override
    public Set<String> getUserPermission(long userId) {
        List<String> permsList=null;
        //超级管理员用户
        if(userId==1)
        {
            List<SysMenu> sysMenus = sysMenuMapper.queryListAll();
            permsList=new ArrayList<String>(sysMenus.size());
            for (SysMenu menu:sysMenus)
            {
                permsList.add(menu.getPerms());
            }
        }
        else
        {
            //通用用户授权
            permsList = sysUserMapper.queryAllPerms(userId);
        }

        System.out.println("-----------用户授权列表："+permsList);

        //用Set主要是让List去重
        Set<String> permsSet=new HashSet<String>();
        for (String perms:permsList)
        {
            if(StringUtils.isBlank(perms))
            {
                continue;//退出for
            }
            //用户资源权限列表用，分割并转化为list
            String[] split = perms.trim().split(",");
            permsSet.addAll(Arrays.asList(split));
        }
        System.out.println("-----------用户授权列表2："+permsSet);
        return permsSet;
    }


}
